<template>
  <a-card :bordered="false">
    <div>
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
          </a-row>
        </a-form>
      </div>

      <div style="margin-bottom: 15px;">
        <span style="font-weight: bold">跟进时间：</span>
        <a-checkable-tag style="font-size: 14px;margin: 5px;padding: 5px" v-for="(item,index) in this.addDateList"
                         :key="index" v-model:checked="item.checkedValue"
                         @change="onChangeAddDate(item.key,item.itemValue)">{{item.itemText}}
        </a-checkable-tag>
        <a-range-picker v-show="this.currentKey" @change="onChangeCustomerAddDate" format="YYYY-MM-DD"
                        v-model:value="dateValue"/>
      </div>
      <div style="margin-bottom: 10px;">
        <span style="font-weight: bold">&nbsp;&nbsp;&nbsp;创建人：</span>
        <a-select
          show-search
          :allowClear="true"
          placeholder="请选择创建人"
          option-filter-prop="children"
          v-model="queryParam.createBy"
          style="width: 180px"
          :filter-option="filterOptionCreateBy"
          @change="changeCreateBy">
          <a-select-option :value="item.realname" v-for="(item,index) in createByData" :key="index">
            {{item.realname}}
          </a-select-option>
        </a-select>
      </div>
    </div>

    <div  ref="myChart" style="height: 300px; width: 100%"></div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <a slot="name" @click="followRecordDetail(record)" slot-scope="text,record">{{ text }}</a>

      </a-table>
    </div>

    <customer-follow-record-modal ref="customerFollowRecordModal"></customer-follow-record-modal>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { filterObj } from '@/utils/util';
  import {mixinDevice} from '@/utils/mixin'
  import {filterDictTextByCache} from '@comp/dict/JDictSelectUtil'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction,putAction} from "@/api/manage";
  import moment from 'moment'
  import customerFollowRecordModal from '../../../customer/highSeas/modules/customerFollowRecordModal'

  export default {
    name: "followRecordCustomer",
    mixins: [JeecgListMixin, mixinDevice],
    components:{
      customerFollowRecordModal,
    },
    data(){
      return {
        description: '新增客户报表',
        showBarDataByTime: false,
        showBarDataByCreate: false,
        currentKey: false,
        startDate: '',
        endDate: '',
        dateValue: [],
        dataSource:[],
        barDataList: [],
        height: 420,
        createByData:[],    //创建人列表
        currentStatisticType: "",  //当前选中的统计类型
        currentTime:"",
        statisticTypeList:[], //统计类型
        addDateList:[], //创建时间
        model:{},
        chooseKey:'',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '客户姓名',
            align: "center",
            dataIndex: 'name',
            scopedSlots: {
              customRender: 'name'
            },
          },
          {
            title: '项目地址',
            align: "center",
            dataIndex: 'address'
          },
          {
            title: '家装顾问',
            align: "center",
            dataIndex: 'homeAdviser',
          },
          {
            title: '设计师',
            align: "center",
            dataIndex: 'designer'
          },
          {
            title: '当前进展',
            align: "center",
            dataIndex: 'progress',
            customRender: (text) => {
              //字典值翻译通用方法
              return filterDictTextByCache('customer_info_progress', text);
            }
          },
          {
            title: '最近跟进时间',
            align: "center",
            dataIndex: 'latelyFollowTime',
          },
          {
            title: '最近跟进内容',
            align: "center",
            dataIndex: 'latelyFollowContent',
          },
          {
            title: '创建人',
            align: "center",
            dataIndex: 'createBy',
          },
        ],
        url: {
          list: "/ghFollowRecord/queryPageBarList",
          getSearchConditionData: "/ghCustomerInfo/getItemsByDictCode",
          queryUserList: "/sys/user/allList",

          queryBarDataList: "/ghFollowRecord/queryBarDataList",
        },
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        barData: 0,
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        currentUserRealName:"",
        xData: [],
      }
    },
    created() {
      this.initSearchConditionData();
      this.loadUserListData();
      this.loadData();
    },
    mounted() {
      let xData = [moment(moment().valueOf()).format("YYYY/MM/DD")];
      let params = {};
      params.currentTime = "today";
      this.loadBarData(params,xData,"YYYY/MM/DD","byTime")
    },
    methods:{
      drawChart(xData,yData) {
        // 基于准备好的dom，初始化echarts实例
        let myChart = this.$echarts.init(this.$refs.myChart);
        // 指定图表的配置项和数据
        let option = {
          xAxis: {
            type: "category",
            data: xData,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              name: "个数",
              data: yData,
              type: "bar",
              label:{
                show: true, //开启显示
                position: "top", //在上方显示
                textStyle: {
                  color: "grey",
                  fontSize: 13,
                }
              },
            },
          ],
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      },
      //创建时间发生变化
      onChangeAddDate(key, itemValue){
        this.chooseKey = key;
        for (let i = 0; i < this.addDateList.length; i++) {
          if (key == this.addDateList[i].key) {
            this.addDateList[i].checkedValue = true;
          } else {
            this.addDateList[i].checkedValue = false;
          }
        }
        if (key == 'key11'){
          this.currentKey = true;
        }else {
          this.currentKey = false;
          this.dateValue = [];
          this.currentTime = itemValue;
          this.loadData(1);
        }
        let xData = [];
        let params = this.getQueryParams();
        params.currentTime = this.currentTime;
        switch (itemValue) {
          case "today":
            xData = [moment(moment().valueOf()).format("YYYY/MM/DD")];
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM/DD","byTime")
            break;
          case "yesterday":
            xData = [moment(moment().add(-1, 'days').startOf('day').valueOf()).format('YYYY/MM/DD')];
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM/DD","byTime")
            break;
          case "currentMonth":
            xData = this.getMonthDays(0);
            this.xData = xData;
            this.loadBarData(params,xData,"MM/DD","byTime")
            break;
          case "lastMonth":
            xData = this.getMonthDays(-1);
            this.xData = xData;
            this.loadBarData(params,xData,"MM/DD","byTime")
            break;
          case "currentWeek":
            xData = this.getWeekDays(0);
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM/DD","byTime")
            break;
          case "lastWeek":
            xData = this.getWeekDays(-1);
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM/DD","byTime")
            break;
          case "currentQuarter":
            xData = this.getQuarterMonths(0)
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM","byTime")
            break;
          case "lastQuarter":
            xData = this.getQuarterMonths(-1)
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM","byTime")
            break;
          case "thisYear":
            xData = this.getYearMonths(0)
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM","byTime")
            break;
          case "lastYear":
            xData = this.getYearMonths(-1)
            this.xData = xData;
            this.loadBarData(params,xData,"YYYY/MM","byTime")
            break;
        }
      },
      //根据条件查询条形图数据
      loadBarData(params,xData,format,byType){
        const yData = [];
        if (byType == "byTime"){
          getAction(this.url.queryBarDataList,params).then((res) => {
            if (res.success) {
              this.barDataList = res.result.records || res.result;
              for (let i = 0; i<xData.length; i++){
                var num = 0;
                for (let j = 0; j<this.barDataList.length; j++){
                  if (moment(this.barDataList[j].latelyFollowTime).format(format) == xData[i]){
                    num++;
                  }
                }
                yData.push(num)
              }
            }
            this.drawChart(xData,yData)
          })
        }else {
          let params = this.getQueryParams();
          params.createBy = this.currentUserRealName;
          if (this.currentTime == ""){
            params.currentTime = "today"
          }else {
            params.currentTime = this.currentTime;
          }
          getAction(this.url.queryBarDataList,params).then((res) => {
            if (res.success) {
              this.barDataList = res.result.records || res.result;
              let xData = [];
              if (this.currentUserRealName == null || this.currentUserRealName == ""){
                xData = this.xData;
              }else {
                xData.push(this.currentUserRealName)
              }
              yData.push(this.barDataList.length)
              this.drawChart(xData,yData)
            }
          })
        }
      },

      //自定义创建时间
      onChangeCustomerAddDate(value, dateString){
        this.startDate = dateString[0];
        this.endDate = dateString[1];
        this.currentTime = "customizeTime";
        this.loadData(1);
      },
      loadData(){
        var params = this.getQueryParams();//查询条件
        params.currentStatisticType = this.currentStatisticType;

        if (this.currentTime != null && this.currentTime != '') {
          params.currentTime = this.currentTime;
          if (this.currentTime == "customizeTime"){
            params.beginTime = this.startDate;
            params.endTime = this.endDate;
          }
        }else {
          params.currentTime = "today";
        }
        getAction(this.url.list,params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result;
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      initSearchConditionData() {
        getAction(this.url.getSearchConditionData).then(res => {
          if (res.success) {
            this.statisticTypeList = res.result.statisticTypeList;
            this.addDateList = res.result.addDateList;
            this.addDateList.splice(0,1);
            this.addDateList.splice(this.addDateList.length-1,1);
            this.addDateList[0].checkedValue = true;
          }
        })
      },
      //加载用户列表
      loadUserListData() {
        getAction(this.url.queryUserList).then((res) => {
          if (res.success) {
            this.createByData = res.result.records||res.result;
          }
        })
      },
      filterOptionCreateBy(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      changeCreateBy(value){
        if (value != null && value != ""){
          this.currentUserRealName = value;
          this.loadData(1);
          this.loadBarData("","","","byCreate")
        }else {

          this.currentUserRealName = value;
          this.loadData(1);
          this.onChangeAddDate(this.chooseKey,this.currentTime);
        }
      },
      getWeekDays(n) {
        let daysList = [];
        for (var i = 0; i < 7; i++) {
          let day = moment(
            moment()
              .week(moment().week() + n)
              .startOf("week")
              .add(i, "days")
              .valueOf()
          ).format("YYYY/MM/DD");
          daysList.push(day);
        }
        return daysList;
      },
      //获取每个月的每一天
      getMonthDays(n) {
        let daysList = [];
        let daysInMonth = moment()
          .month(moment().month() + n)
          .daysInMonth(); // 当前月天数
        for (var i = 0; i < daysInMonth; i++) {
          let day = moment(
            moment()
              .month(moment().month() + n)
              .startOf("month")
              .add(i, "days")
              .valueOf()
          ).format("MM/DD");
          daysList.push(day);
        }
        return daysList;
      },
      //获取季度月份
      getQuarterMonths(n){
        let daysList = [];
        let currentQuarter = moment()
          .quarter(moment().quarter() + n).month() + 1; // 当前月
        for (var i = 0; i < 3; i++) {
          let month = moment(
            moment()
              .quarter(moment().quarter() + n)
              .startOf("quarter")
              .add(i, "month")
              .valueOf()
          ).format("YYYY/MM");
          daysList.push(month);
        }
        return daysList;
      },
      //获取年度月份
      getYearMonths(n){
        let daysList = [];
        let currentYear = moment()
          .year(moment().year() + n).year(); // 当前年
        for (var i = 0; i < 12; i++) {
          let month = moment(
            moment()
              .year(moment().year() + n)
              .startOf("year")
              .add(i, "month")
              .valueOf()
          ).format("YYYY/MM");
          daysList.push(month);
        }
        return daysList;
      },
      //跟进记录
      followRecordDetail(record){
        this.$refs.customerFollowRecordModal.pageIntoType = 2;
        this.$refs.customerFollowRecordModal.currentCustomerId = record.id;
        this.$refs.customerFollowRecordModal.currentHighSeas = record.highSeasDepot;
        this.$refs.customerFollowRecordModal.getCustomerFollowInfo()
        this.$refs.customerFollowRecordModal.visible = true;
        this.$refs.customerFollowRecordModal.currentHighSeasCustomer = record;
        this.$refs.customerFollowRecordModal.title = "客户 " + record.name + " 的跟进记录";
      },
    }
  }
</script>

<style scoped>

</style>